# -*- coding: utf-8 -*-

#Playwright Python库优雅地处理文件上传操作，包括直接上传文件和处理需要弹出文件选择器的情况。
# 通过locator.set_input_files()方法和监听filechooser事件

from playwright.sync_api import sync_playwright




def run(playwright):
    chromium = playwright.chromium
    browser = chromium.launch(headless=False, slow_mo=3000)
    page = browser.new_page()
    #1、文件上传是input输入框，并且type=“file”的情况
    page.goto("xxx")
    page.get_by_label("选择文件").set_input_files('tou.png')# 不点开文件框的情况下

    #2、不是input输入框，必须点开文件框的情况下，可以使用expect_file_chooser()监听到弹出框，在弹出框输入文件路径
    # 点击选择文件，输入文件
    with page.expect_file_chooser() as fc_info:
        page.get_by_label("选择文件").click()
    page.pause()
    file_chooser = fc_info.value
    file_chooser.set_files(r"D:\tou.png")

    #异步操作
    async with page.expect_file_chooser() as fc_info:
        await page.get_by_label("选择文件").click()
    file_chooser = await fc_info.value
    await file_chooser.set_files("myfile.pdf")

    #高级操作-事件监听filechooser
    #page.on("filechooser",) 会自动监听到filechooser事件，只要点击了选择文件按钮就会自动触发上传文件
    page.on("filechooser", lambda file_chooser: file_chooser.set_files(r"D:\tou.png"))
    # 点击选择文件按钮，会触发 filechooser 事件
    page.get_by_label("选择文件").click()



if __name__ == '__main__':
    with sync_playwright() as playwright:
        run(playwright)





